package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    @Override
    public void deductBalance(Long id, Integer amount) {
        //判断用户状态是否正常
        User user = this.getById(id);
        if (user == null || user.getStatus() == UserStatus.FREEZE){
            throw new RuntimeException("用户状态不正常");
        }
        //判断余额是否充足
        if (user.getBalance() < amount){
            throw new RuntimeException("余额不足");
        }
        //扣减余额
//        userMapper.deductBlanceById(id, amount);
        //获取扣减后余额
        int remainBalance = user.getBalance() - amount;
        this.lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁
                .update();
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        User user = getById(id);
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);

        List<Address> addressList = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        List<AddressVO> addressVOS = BeanUtil.copyToList(addressList, AddressVO.class);
        userVO.setAddresses(addressVOS);
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        List<User> users = listByIds(ids);
        List<UserVO> userVOS = BeanUtil.copyToList(users, UserVO.class);

        List<Address> addresses = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, ids)
                .list();
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        Map<Long, List<AddressVO>> addressMap = addressVOS.stream()
                .collect(Collectors.groupingBy(AddressVO::getUserId));

        for (UserVO userVO : userVOS){
            List<AddressVO> addressVOList = addressMap.get(userVO.getId());
            userVO.setAddresses(addressVOList);
        }

        return userVOS;
    }
}
